from flask import Flask, render_template, request, jsonify, session
from uuid import uuid4
import os
from config import Config
from chatbot import MultiModelChatbot

app = Flask(__name__)
app.secret_key = os.getenv('FLASK_SECRET_KEY')

@app.route("/")
def index():
    # 为每个会话创建唯一 ID
    if 'session_id' not in session:
        session['session_id'] = str(uuid4())
    return render_template("index.html")

@app.route("/chat", methods=["POST"])
def chat():
    try:
        data = request.get_json()
        user_message = data.get("message", "").strip()
        conversation_history = data.get("history", [])
        selected_model = data.get("model", "chatgpt")  # 默认使用 chatgpt

        if not user_message:
            return jsonify({"response": "请输入内容~", "error": False})

        # 获取响应
        response = MultiModelChatbot.get_response(user_message, conversation_history, selected_model)

        return jsonify({
            "response": response,
            "error": False,
            "session_id": session.get('session_id')
        })

    except Exception as e:
        return jsonify({
            "response": f"抱歉，服务器处理请求时出现错误: {e}",
            "error": True
        }), 500

@app.route("/config", methods=["GET"])
def get_config():
    """获取当前配置信息"""
    return jsonify({
        "model": Config.SELECTED_MODEL,
        "api_configured": bool(Config.API_KEYS.get(Config.SELECTED_MODEL)),
        "max_tokens": Config.MAX_TOKENS,
        "temperature": Config.TEMPERATURE
    })

if __name__ == "__main__":
    app.run(debug=True, host='0.0.0.0', port=8080)
